﻿using UnityEngine;
using System.Collections;

public class PlayerMove : MonoBehaviour
{
    NavMeshAgent agent;

    public Transform bullet;

    Vector3 targetPos;

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();

        changeTarget();
        StartCoroutine(moving());
        StartCoroutine(firing());
    }

    void changeTarget()
    {
        targetPos = transform.parent.TransformPoint(new Vector3(Random.Range(-900, 900), 0, Random.Range(-900, 900)));
        agent.SetDestination(targetPos);
    }

    void fire()
    {
        var b = Instantiate(bullet);
        b.position = transform.position - transform.forward * 6;
        b.LookAt(transform.position - transform.forward * 8);
    }

    IEnumerator moving()
    {
        while (true)
        {
            Vector3 dis = targetPos - transform.position;
            if (Mathf.Abs(dis.x) < 10 && Mathf.Abs(dis.z) < 10)
                changeTarget();
            else
                yield return null;
        }
    }


    IEnumerator firing()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            fire();
        }
    }
}
